using System;
using System.Collections.Generic;
using System.Linq;

namespace TicTacToe
{
    /// <summary>
    /// Holds the current rule-set for the game
    /// </summary>
    public static class GameRules
    {
        /// <summary>
        /// Toss a coin to see who goes first.
        /// </summary>
        /// <returns>True for heads, false for tails.</returns>
        public static bool CoinToss()
        {
            return (new Random().Next() % 2) == 0;
        }

        /// <summary>
        /// Checks whether any more moves should be made on the supplied board.
        /// </summary>
        /// <returns>True if the board is complete, either because someone won or because it's full.</returns>
        public static bool IsComplete(this Board board)
        {
            return board.IsWon() || board.IsFull();
        }

        /// <summary>
        /// Checks whether the supplied board has been won.
        /// </summary>
        /// <returns>True if any scoring lines have been completed with a single symbol.</returns>
        public static bool IsWon(this Board board)
        {
            return board.HasCompleteRow() ||
                   board.HasCompleteColumn() ||
                   board.HasCompleteDiagonal();
        }

        /// <summary>
        /// Checks whether the supplied board has been drawn.
        /// </summary>
        /// <returns>True if the board is full and neither player has won.</returns>
        public static bool IsDrawn(this Board board)
        {
            return board.IsFull() && !board.IsWon();
        }

        private static bool HasCompleteRow(this Board board)
        {
            return board.GetAllRows().Any(r => r.AllCellsArePopulatedAndMatch());
        }

        private static bool HasCompleteColumn(this Board board)
        {
            return board.GetAllColumns().Any(c => c.AllCellsArePopulatedAndMatch());
        }

        private static bool HasCompleteDiagonal(this Board board)
        {
            return board.GetCellsOnForwardDiagonal().AllCellsArePopulatedAndMatch() ||
                   board.GetCellsOnBackwardsDiagonal().AllCellsArePopulatedAndMatch();
        }
    }
}